<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="菜品名称" prop="dishName">
        <el-input
          v-model="queryParams.dishName"
          placeholder="请输入菜品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dishList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="菜品名称" align="center" prop="dishName"/>
      <el-table-column label="菜品描述" align="center" prop="description"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改菜品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="菜品名称" prop="dishName">
          <el-input v-model="form.dishName" placeholder="请输入菜品名称"  style="width: 700px"/>
        </el-form-item>
        <el-form-item label="菜品描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入菜品描述" style="width: 700px"/>
        </el-form-item>
        <!-- 配料管理模块 -->
        <el-form-item label="配料清单">
          <el-table :data="form.materials || []" border  style="width: 700px" size="mini"  header-row-class-name="custom-header">
            <el-table-column label="配料名称" prop="materialName"  width="180"  show-overflow-tooltip>
              <template slot-scope="scope">
                <el-select
                  v-if="scope.row.editMode || !scope.row.materialId"
                  @focus="scope.row.editMode = true"
                  v-model="scope.row.materialId"
                  filterable
                  remote
                  :remote-method="searchMaterial"
                  placeholder="输入配料名称搜索"
                  :loading="searchLoading"
                  :disabled="!scope.row.isNew"
                  @change="val => handleMaterialChange(scope.row, val)"
                >
                  <!-- 加载中的提示 -->
                  <el-option v-if="searchLoading" value="loading" disabled label="加载中..."/>
                  <el-option
                    v-for="item in getAvailableMaterials(scope.row)"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name">
                  </el-option>
                </el-select>
                <span v-else>{{ scope.row.materialName }}</span>
              </template>
            </el-table-column>

            <el-table-column  label="数量"
                              width="230"
                              align="center">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.quantity"
                                 @change="handleQuantityChange(scope.row)"
                                 :min="0.01"
                                 :step="0.1"
                                 :precision="2"/>
              </template>
            </el-table-column>

            <el-table-column  label="单位"
                              width="90"
                              align="center">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.unit"
                  :disabled="!!scope.row.materialId"
                />
              </template>
            </el-table-column>

            <el-table-column  label="品类"
                              width="120"
                              align="center">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.category"
                  :disabled="!!scope.row.materialId"
                />
              </template>
            </el-table-column>

            <el-table-column label="操作"
                             width="80"
                             align="center">
              <template slot-scope="scope">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="removeMaterial(scope.$index)"/>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 10px">
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="addMaterial">添加配料
            </el-button>
          </div>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 菜品导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                 :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                 :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>
            是否更新已经存在的菜品信息
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listDish, getDish, delDish, addDish, updateDish} from "@/api/catering/dish";
import {getToken} from "@/utils/auth";
import {listMaterial} from "@/api/catering/material";

export default {
  name: "Dish",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 菜品表格数据
      dishList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 菜品导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/dish/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dishName: null,
        description: null,
      },
      // 表单参数
      form: {},

      materialOptions: [],   // 原料搜索选项
      searchLoading: false,  // 搜索加载状态
      // unitOptions: [
      //   {label: '斤', value: '斤'},
      //   {label: '公斤', value: '公斤'},
      //   {label: '克', value: '克'},
      //   {label: '千克', value: '千克'},
      //   {label: '毫升', value: '毫升'},
      //   {label: '升', value: '升'},
      //   {label: '个', value: '个'},
      //   {label: '勺', value: '勺'}
      // ],
      // 表单校验
      rules: {
        dishName: [
          {required: true, message: "菜品名称不能为空", trigger: "blur"}
        ],
        materials: [
          {
            validator: (rule, value, callback) => {
              const isValid = (value || []).every(m =>
                m.materialId && m.quantity > 0
              );
              return isValid
                ? callback()
                : callback(new Error('请完善所有配料信息'));
            },
            trigger: 'blur'
          }
        ]
      }
    };
  },
  created() {
    this.getList();
    if (this.$route.params.id) {
      // 编辑模式：获取数据后初始化
      this.fetchData()
    }
  },
  methods: {
    async fetchData() {
      const res = await getDishDetail(this.$route.params.id)
      this.initForm(res.data) // 关键初始化调用
    },
    initForm(originalData) {
      this.form.materials = originalData.materials.map(m => ({
        ...m,
        isNew: false // 标记为已有数据
      }))
    },
    /** 查询菜品列表 */
    getList() {
      this.loading = true;
      listDish(this.queryParams).then(response => {
        this.dishList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        dishName: null,
        description: null,
        materials: [],
      };
      this.originalMaterials = []; // 重置时清空原始数据
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加菜品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id || this.ids;
      getDish(id).then(response => {
        // 深拷贝原始数据（包含materialId）
        this.originalMaterials = (response.data.materials || []).map(m => ({
          materialId: m.materialId,
          quantity: m.quantity
        }));

        // 初始化表单数据
        this.form = {
          ...response.data,
          materials: (response.data.materials || []).map(m => ({
            materialId: m.materialId,
            materialName: m.materialName,
            unit: m.unit,
            category: m.category,
            quantity: m.quantity,
            editMode: false,
            tempId: Date.now()
          }))
        };
        this.originalMaterials = [...response.data.materials];
        this.open = true;
        this.title = "修改菜品";
      });
    },
    searchMaterial: _.debounce(function(query) {
      if (!query) {
        this.materialOptions = []
        return
      }

      this.searchLoading = true
      listMaterial({ name: query }).then(res => {
        this.materialOptions = res.rows
      }).finally(() => {
        this.searchLoading = false
      })
    }, 500),
    // 获取可用原料（排除已选）
    getAvailableMaterials(currentRow) {
      const selectedIds = this.form.materials
        .filter(m => m !== currentRow)
        .map(m => m.materialId)
        .filter(Boolean)

      return this.materialOptions.filter(
        item => !selectedIds.includes(item.id)
      )
    },

    // 原料选择处理
    handleMaterialChange(row, materialId) {
      // 检查是否重复
      const exists = this.form.materials.some(
        m => m !== row && m.materialId === materialId
      )

      if (exists) {
        this.$message.error('该原料已存在，不可重复添加')
        row.materialId = null
        row.unit = null
        row.category = null // {{变更}} 清空品类
        return
      }
      // 自动填充单位和品类
      const material = this.materialOptions.find(m => m.id === materialId)
      if (material) {
        row.unit = material.unit
        row.category = material.category // {{变更}} 填充品类
        row.materialName = material.name
      } else {
        // {{变更}} 如果找不到material（理论上不应发生），也清空
        row.unit = null
        row.category = null
      }
      row.editMode = false
      this.$nextTick(() => this.$forceUpdate())
    },
    // <变更> 修改添加配料方法
    addMaterial() {
      this.form.materials.push({
        materialId: null,
        quantity: null,
        unit: null, // {{变更}} 初始化unit
        category: null, // {{变更}} 初始化category
        isNew: true,
        editMode: true
      });
      // 自动聚焦新行（可选增强）
      this.$nextTick(() => {
        const inputs = document.querySelectorAll('.el-select__input')
        if (inputs.length > 0) {
          inputs[inputs.length - 1].focus()
        }
      })
    },

    // 删除配料行
    removeMaterial(index) {
      this.form.materials.splice(index, 1);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 构建配料变更数据
          const payload = {
            addList: [],
            updateList: [],
            deleteList: []
          };

          // 处理新增配料（仅标记为isNew且materialId存在）
          payload.addList = this.form.materials
            .filter(m => m.isNew && m.materialId)
            .map(m => ({
              materialId: m.materialId,
              quantity: m.quantity
            }));

          // 处理更新配料（比较原始数据）
          payload.updateList = this.form.materials
            .filter(m => {
              if (m.isNew) return false;
              const original = this.originalMaterials.find(
                om => om.materialId === m.materialId
              );
              return original && Number(original.quantity) !== Number(m.quantity);
            })
            .map(m => ({
              materialId: m.materialId,
              quantity: parseFloat(m.quantity)
            }));

          // 处理删除配料（原始存在但当前不存在）
          const currentIds = this.form.materials.map(m => m.materialId);
          payload.deleteList = this.originalMaterials
            .filter(om => !currentIds.includes(om.materialId))
            .map(om => om.materialId);

          // 构建完整的请求数据（包含菜品基本信息）
          const requestData = {
            id: this.form.id,           // 确保包含菜品ID
            dishName: this.form.dishName,
            description: this.form.description,
            ...payload                  // 展开配料变更数据
          };

          // 调用API方法
          const apiMethod = this.form.id ? updateDish : addDish;
          apiMethod(requestData).then(() => {
            this.$modal.msgSuccess("操作成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    handleQuantityChange(row) {
      // 标记修改并保留两位小数
      row._isModified = true;
      row.quantity = Number(row.quantity.toFixed(2));
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除菜品编号为"' + ids + '"的数据项？').then(function () {
        return delDish(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "菜品导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/dish/importTemplate', {}, `dish_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
}
;
</script>
<style scoped>
/* 表格头样式优化 */
.custom-header th {
  background-color: #f5f7fa;
  color: #606266;
}

/* 统一输入框和表格的过渡效果 */
.el-input, .el-table {
  transition: all 0.3s ease;
}

/* 表格行高优化 */
.el-table::v-deep .el-table__row td {
  padding: 8px 0;
}
</style>
